import time
import re
import json
import urllib
import scrapy
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
import math
import requests
import base64
from urllib.parse import urlencode


class spider(BaseTaxPolicySpider):
    name = "sichuan_dzsdcqrmzfzfbwj"

    province: str = "四川省"  # 取表格
    city: str = "达州市"  # 取表格
    county: str = "达川区"  # 取表格
    park: str = "None"  # 取表格
    source: str = "达州市达川区人民政府"  # 取表格 同一个来源合并
    url: str = "http://www.dachuan.gov.cn/xxgk-list-zfbwj.html"  # 注明入口网址，以便后续排错
    headers = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Origin": "http://www.tchuan.gov.cn",
        "Pragma": "no-cache",
        "Referer": "http://www.tchuan.gov.cn/xxgk-list-%20qzfbwj.html",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest"
    }
    doc_list = [
        "http://www.dachuan.gov.cn/api-ajax_list-1.html",

    ]

    def start_requests(self):
        for url in self.doc_list:
            payload = "ajax_type%5B%5D=42_xxgk&ajax_type%5B%5D=1570&ajax_type%5B%5D=42&ajax_type%5B%5D=xxgk&ajax_type%5B%5D=Y-m-d&ajax_type%5B%5D=34&ajax_type%5B%5D=30&ajax_type%5B%5D=0&ajax_type%5B8%5D=&is_ds=1"
            response = requests.post(url, headers=self.headers, data=payload, verify=False)

            total_num = json.loads(response.text)['total']
            rows = 30
            pages = int(math.ceil(int(total_num) / int(rows)))
            print("总页数：", pages, "总条数：", total_num)
            for page in range(1, pages + 1):
                # 发送GET请求
                url = f"http://www.dachuan.gov.cn/api-ajax_list-{page}.html"
                yield scrapy.Request(url=url, method='POST', headers=self.headers, body=payload, callback=self.detail_requests)

    def detail_requests(self, response, **kwargs):
        item_list = json.loads(response.text)['data']

        for item in item_list:
            url = item['url']
            yield scrapy.Request(url=url, method='GET', headers=self.headers, callback=self.parse_detail)

    def parse_list(self, response, **kwargs):
        pass

    def parse_detail(self, response=None, **kwargs):
        item = Item()
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['source_url'] = response.url
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(".").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        if '已失效' in item['title'] or '已废止' in item['title']:
            item['state'] = '0'
        else:
            item['state'] = None
        # print("item", item)
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl sichuan_dzsdcqrmzfzfbwj".split())
